﻿using System.Windows;
using Gavel.Common.Component.Controls;
using Gavel.Common.Utilities.Const;
using Gavel.Common.Utilities.Model;
using Gavel.ModLink.Helper;
using Gavel.ModLink.Model;
using Gavel.ModLink.ViewModel;

namespace Gavel.ModLink.Views;

/// <summary>
/// 寄存器数据视图
/// </summary>
public partial class RegisterView
{
    /// <summary>
    /// 视图模型
    /// </summary>
    private readonly RegisterViewModel _viewModel;
    
    /// <summary>
    /// 修改寄存器值事件
    /// </summary>
    public event Action<RegisterValue>? OnEditRegisterValueEvent;

    /// <summary>
    /// 默认构造
    /// </summary>
    public RegisterView()
    {
        InitializeComponent();
        _viewModel = (RegisterViewModel)DataContext;
        ClientHelper.Instance.ReceivedEvent += Received;
        ClientHelper.Instance.SocketStatusChangedEvent += SocketStatusChanged;
    }

    /// <summary>
    /// 数据接收处理
    /// </summary>
    /// <param name="transmit">报文传输</param>
    private void Received(MessageTransmit transmit)
    {
        if (transmit.Function is FunctionType.WriteSingle or FunctionType.WriteMultiple)
        {
            return;
        }

        _viewModel.Received(transmit);
    }

    /// <summary>
    /// 套接字状态改变事件
    /// </summary>
    /// <param name="status">套接字状态</param>
    private void SocketStatusChanged(SocketStatus status)
    {
        if (status == SocketStatus.Normal)
        {
            _viewModel.Values = [];
        }
    }

    /// <summary>
    /// 修改寄存器点击事件
    /// </summary>
    /// <param name="sender">事件发送者</param>
    /// <param name="e">事件参数</param>
    private void EditRegisterClick(object sender, RoutedEventArgs e)
    {
        if (sender is not IconButton { CommandParameter: RegisterValue registerValue })
        {
            return;
        }
        
        OnEditRegisterValueEvent?.Invoke(registerValue);
    }
}